﻿// -----------------------------------------------------------------------
// <copyright file="ColorConvertor.cs">
// Copyright (c) 2013 Andrey Veselov. All rights reserved.
// License:  Microsoft Public License (MS-PL)
// Contacts: http://andrey.moveax.com  andrey@moveax.com
// </copyright>
// -----------------------------------------------------------------------

namespace PortableImagingLibrary.Convertors
{
    using System;
    using System.Diagnostics.Contracts;

    internal static class ColorConvertor
    {
        public static uint RgbBytesTo8BitColor(byte[] source, int startIndex)
        {
            Contract.Requires(startIndex >= 0);
            Contract.Requires(source != null);
            Contract.Requires(source.Length >= (startIndex + 3));

            const byte alpha = 255; // alpha channel value

            return (uint)((alpha << 24)
                + (source[startIndex] << 16)
                + (source[startIndex + 1] << 8)
                + source[startIndex + 2]);
        }

        public static uint Conver16BitArrayTo8BitColor(byte[] source, int startIndex, bool treatAs8Bit)
        {
            Contract.Requires(startIndex >= 0);
            Contract.Requires(source != null);
            Contract.Requires(source.Length >= (startIndex + 6));

            if (!treatAs8Bit)
                throw new NotSupportedException("16 bit not supported");

            const byte alpha = 255; // alpha channel value

            return (uint)((alpha << 24)
                + (source[startIndex + 1] << 16)
                + (source[startIndex + 3] << 8)
                + source[startIndex + 5]);
        }

        public static byte[] Convert8BitColorTo16BitArray(uint color)
        {
            Contract.Ensures(Contract.Result<byte[]>() != null);
            Contract.Ensures(Contract.Result<byte[]>().Length == 6);

            var data = new byte[6];

            data[0] = 0;
            data[1] = ByteConvertor.GetByte(color, 2);
            data[2] = 0;
            data[3] = ByteConvertor.GetByte(color, 1);
            data[4] = 0;
            data[5] = ByteConvertor.GetByte(color, 0);

            return data;
        }
    }
}
